package ink.onei.feed.utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: dang
 * @Description: TODO
 * @Date: 2024/3/19 10:24 星期二
 */
public class DingUtil {
    private static final String SECRET = "SECf1671f249699e47dfff7a9b2cde13e5cba1d8d3f5fa06f2c291d6b9d59bc74fa";
    private static final String URL = "https://oapi.dingtalk.com/robot/send?access_token=cb7c75e4b79f2a68bcc3f9595e647ac5c9d128a69c1d9e7756077e9e8eb4b4ae";

    public static void send(String content) {

        try {
            Long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + SECRET;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(SECRET.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            String signResult = "&timestamp=" + timestamp + "&sign=" + sign;
            // 得到拼接后的 URL
            String url = URL + signResult;

            DingTalkClient client = new DefaultDingTalkClient(url);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("text");
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent(content);
            request.setText(text);
            OapiRobotSendResponse response = client.execute(request);
        } catch (ApiException | NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

}
